package jwt

import (
	"crypto"
	"crypto/hmac"
	_ "crypto/sha256"
	"encoding/base64"
)

type hmacAlgorithm struct {
	crypto.Hash
}

var HS256 = &hmacAlgorithm{crypto.SHA256}

func (a *hmacAlgorithm) Sign(raw, secret string) (sign string, err error) {
	return base64.RawURLEncoding.EncodeToString(a.digest(raw, secret)), nil
}

func (a *hmacAlgorithm) Verify(raw, sign, secret string) (access bool, err error) {
	var signDigest []byte
	if signDigest, err = base64.RawURLEncoding.DecodeString(sign); nil != err {
		return false, err
	}

	digest := a.digest(raw, secret)

	return hmac.Equal(digest, signDigest), nil
}

func (a *hmacAlgorithm) digest(raw, secret string) (digest []byte) {
	h := hmac.New(a.New, []byte(secret))
	h.Write([]byte(raw))

	return h.Sum(nil)
}
